package cn.wen.yinxiu.member.server.socket.handler;

import cn.wen.yinxiu.common.constant.Constant;
import cn.wen.yinxiu.common.to.system.NoticeTO;
import cn.wen.yinxiu.common.toolkit.SocketChannelUtil;
import cn.wen.yinxiu.member.server.protocol.Command;
import cn.wen.yinxiu.member.server.protocol.friend.AddFriendRequest;
import cn.wen.yinxiu.member.server.protocol.friend.AddFriendResponse;
import cn.wen.yinxiu.member.server.protocol.login.LoginResponse;
import cn.wen.yinxiu.member.service.UsersService;
import cn.wen.yinxiu.member.vo.UserFriend;
import cn.wen.yinxiu.member.vo.UserInfo;
import com.alibaba.fastjson.JSONObject;
import io.netty.buffer.ByteBuf;
import io.netty.channel.Channel;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.handler.codec.http.websocketx.TextWebSocketFrame;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.List;


/**
 * @ClassName: AddFriendHandler
 * @Author: 小飞
 * @Date: 2023/5/28 14:34
 * @Description: 添加朋友处理类
 */
@Slf4j
public class AddFriendHandler extends SimpleChannelInboundHandler<AddFriendRequest> {

    private final UsersService userService;

    public AddFriendHandler(UsersService userService) {
        this.userService = userService;
    }

    @Override
    protected void channelRead0(ChannelHandlerContext ctx, AddFriendRequest msg) {
        // 1. 添加关注到数据库中[A->B] （只有双方相互关注才能成为好友）
        List<UserFriend> userFriendList = new ArrayList<>();
        userFriendList.add(new UserFriend(msg.getUserId(), msg.getFriendId()));
        userService.addUserFriend(userFriendList);
        // 2. 推送好友添加完成 A
        UserInfo userInfo = userService.queryUserInfo(msg.getFriendId());
        // 3.获取当前的Channel 需要响应关注成功
        Channel channel = ctx.channel();
        AddFriendResponse userInfoResponse = new AddFriendResponse(userInfo.getUserId(), userInfo.getNickname(),
                userInfo.getUserAvatar(), userInfo.getUserSignature());
        JSONObject params = new JSONObject();
        params.put("userId", msg.getUserId());
        params.put("friendInfo", userInfoResponse);
        channel.writeAndFlush(new TextWebSocketFrame(getByteBuf(ctx, Command.AddFriendResponse, params)));
        // 4. 需要发送通知 关注成功
        Channel friendChannel = SocketChannelUtil.getChannel(msg.getFriendId());
        // 对方未实现 则不需要netty通知 只需要添加到通知中就行
        UserInfo meInfo = userService.queryUserInfo(msg.getUserId());
        NoticeTO notice = new NoticeTO();
        notice.setActionType(Constant.NoticeType.FOLLOW.getType());
        notice.setContent(Constant.NoticeType.FOLLOW.getInfo());
        notice.setRecipientId(msg.getUserId());
        notice.setSenderId(msg.getFriendId());
        notice.setSenderAvatar(meInfo.getUserAvatar());
        // 通知落到数据库
        NoticeTO noticeTO = userService.addNoticeInfo(notice);
        // 如果对方未上线
        if (null == friendChannel) return;
        JSONObject friendParams = new JSONObject();
        friendParams.put("userId", userInfo.getUserId());
        friendParams.put("noticeInfo", noticeTO);
        // 响应到对方的管道中
        friendChannel.writeAndFlush(new TextWebSocketFrame(getByteBuf(ctx, Command.NoticeResponse, friendParams)));
    }

    public ByteBuf getByteBuf(ChannelHandlerContext ctx, Byte type, JSONObject params) {
        ByteBuf bytebuf = ctx.alloc().buffer();
        JSONObject data = new JSONObject();
        data.put("type", type);
        data.put("code", 200);
        data.put("data", params);
        log.info("返回数据：{}", data);
        byte []bytes = data.toJSONString().getBytes(Charset.forName("utf-8"));
        bytebuf.writeBytes(bytes);
        return bytebuf;
    }
}
